import { Form, Input, Radio } from 'antd';
import { ModelerService } from '@/pages/workflow/model/components/modeler/ModelerService';
import { useEffect, useState } from 'react';

export const Data = (props: { modelerService: ModelerService }) => {
  const [form] = Form.useForm();
  const [type, setType] = useState('gemini');

  const updateValue = () => {
    const value = form.getFieldsValue();
    setType(value.dataType);
    props.modelerService.setCustomerExtensionElement(
      'dataUrl',
      value.dataType === 'gemini'
        ? 'http://everydata/data/' + value.dataKey + '/${businessKey}'
        : value.dataUrl,
    );
  };

  useEffect(() => {
    const url = props.modelerService?.customerExtension?.dataUrl;
    if (url) {
      const start = url.indexOf('http://everydata/data/');
      const configType = start === 0 ? 'gemini' : 'other';
      setType(configType);
      let key = null;

      if (configType === 'gemini') {
        const end = url.indexOf('/', 22);
        key = url.substring(22, end);
      }

      form.setFieldsValue({
        dataType: configType,
        dataUrl: url,
        dataKey: key,
      });
    }
  }, [props.modelerService.element]);

  return (
    <Form layout="vertical" form={form}>
      <Form.Item label="数据源" name="dataType">
        <Radio.Group onChange={updateValue} value={type}>
          <Radio value="gemini">内置</Radio>
          <Radio value="other">外部</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="数据地址" name="dataUrl" hidden={type === 'gemini'}>
        <Input.TextArea rows={8} onBlur={updateValue} />
      </Form.Item>
      <Form.Item label="数据Key" name="dataKey" hidden={type !== 'gemini'}>
        <Input onBlur={updateValue} />
      </Form.Item>
    </Form>
  );
};
